<?php
class Administrator_SeopageController extends Zend_Controller_Action
{
	public $deniedIds = '20,21,22';
	public function init() {

	}

	public function indexAction(){
		$objSeopage = new HT_Model_administrator_models_seopage();
		$do = @$this->_request->getParam('do');
		$id = (int)$this->_request->getParam('id');
		if($do == 'delete' && $id >0){
			$this->deleteSeopage($id);
		}elseif($do == 'exportKeyword'){
			$this->exportKeyword();
		}elseif($do == 'list'){
			$this->getListSeopage();
		}elseif($do == 'ajaxAutoMark'){
			$this->doAjaxAutoMark();
		}elseif($do == 'ajaxAutoLink'){
			$this->doAjaxAutoLink();
		}elseif($do == 'ajaxSitemap'){
			$this->doAjaxSitemap();
		}elseif($do == 'ajaxGroup'){
			$this->doAjaxGroup();
		}elseif($do == 'setNewsKeywords'){
			$this->setNewsKeywords();
		}elseif($do == 'setRSS'){
			$this->setRSS();
		}elseif($do == 'resendGoogle'){
			$this->resendGoogle();
		}elseif($do == 'exportKeywords'){
			$this->exportKeywords();
		}elseif($do == 'exportNewsKeywords'){
			$this->exportNewsKeywords();
		}else{
			$keyword = $this->_request->getParam('keyword');
			$this->view->keyword 	= $keyword;
		}
		$this->view->inlineScript()->appendFile(WEB_PATH.'/application/modules/administrator/views/scripts/seopage/index.js');
	}

	public function rssAction(){
		$objUtil 				= new HT_Model_administrator_models_utility();
		$objSeopage 			= new HT_Model_administrator_models_seopage();
		$rssData 				= $objSeopage->buildRSS();
		$filePath				= ROOT_PATH.'/public/sitemap/rss.xml';
		$message				= $objUtil->overWriteFile($filePath,$rssData);

		$this->view->message 	= $message;
	}

	public function resendGoogle(){
		$objSeopage 	= new HT_Model_administrator_models_seopage();
		$ids 			= @$this->_request->getParam('ids');

		$objSeopage->resendGoogle($ids);
		echo "<b>Từ khóa</b> đã được cập nhật để gửi lại cho google";
		die();
	}

	public function setRSS(){
		$objSeopage 	= new HT_Model_administrator_models_seopage();
		$ids 			= @$this->_request->getParam('ids');
		$rss 			= @$this->_request->getParam('rss');
		$objSeopage->setRSS($ids,$rss);
		echo "Dữ liệu <b>RSS</b> đã được cập nhật";
		die();
	}

	public function setNewsKeywords(){
		$objSeopage 	= new HT_Model_administrator_models_seopage();
		$ids 			= @$this->_request->getParam('ids');
		$keywords 		= @$this->_request->getParam('seo_keywords');
		$objSeopage->setNewsKeywords($ids,$keywords);
		echo "Dữ liệu <b>Từ khóa của tin</b> đã được cập nhật";
		die();
	}

	public function resetindexingAction(){
		$objSeopage 			= new HT_Model_administrator_models_seopage();
		$totalKey				= $objSeopage->resetIndexing();
		$this->view->totalKey 	= $totalKey;
	}

	public function indexingAction(){

		$do 		= @$this->_request->getParam('do');
		$from 		= @$this->_request->getParam('from');
		$to 		= @$this->_request->getParam('to');
		$content 	= null;
		if(!$from) $from = 0;
		if($do == 'submit'){
			$content = @$this->_request->getParam('content');
		}elseif($to >0){
			for($i=$from;$i<=$to;$i++){
				$requestUrl = 'https://www.google.com.vn/search?q=site%3Awish.vn%2Fnen-doc&ie=utf-8&oe=utf-8&aq=t&rls=org.mozilla:en-US:official&client=firefox-a#q=site:wish.vn/nen-doc&client=firefox-a&hs=kOi&rls=org.mozilla:en-US:official&psj=1&ei=3ji4UeaOEsjWkgXA24G4Bw&sa=N&bav=on.2,or.r_qf.&bvm=bv.47810305,d.dGI&fp=2950725cdc695d31&biw=1366&bih=617';
				$requestUrl .= '&start='.$i*10;
				echo $requestUrl."<br>";
				$content .= file_get_contents($requestUrl);
			}
		}

		if($content){
			$data = $this->_getGoogleIndexed($content);
			$data = implode(',', $data);
			$this->view->data 	= $data;
		}

		$this->view->inlineScript()->appendFile(WEB_PATH.'/application/modules/administrator/views/scripts/seopage/indexing.js');
	}

	private function _getGoogleIndexed($content){
		$objSeopage 	= new HT_Model_administrator_models_seopage();
		$arr = explode('nen-doc/',$content);
		$arrData = array();
		for($i=1;$i<sizeof($arr);$i++){
			list($data,$info) = explode('.html',$arr[$i]);
			$arr1 = explode('-',$data);
			$arrData[] = $arr1[sizeof($arr1)-1];
		}
		if(is_array($arrData) && sizeof($arrData) >0){
			$objSeopage->updateGoogleIndexing($arrData);
		}
		return $arrData;
	}

	public function doAjaxGroup(){
		$objSeogroup 	= new HT_Model_administrator_models_seogroup();
		$objSeogroup->suggestGroup(500,3);
		$result 		= '<div class="auto_result">GRP</div><div class="auto_result_text">Nhóm tin đã được cập nhật</div>';
		echo $result; die();
	}

	public function doAjaxSitemap(){
		$objUtil 					= new HT_Model_administrator_models_utility();
		$sitemapData 				= $this->buildXMLSitemap();
		$filePath					= ROOT_PATH.'/public/sitemap/sitemap.xml';
		$message					= $objUtil->overWriteFile($filePath,$sitemapData);
		if($message == 'done'){
			$result = '<div class="auto_result">XML</div><div class="auto_result_text">Đã được cập nhật thành công</div>';
		}else{
			$result = '<div class="auto_result">ERROR</div><div class="auto_result_text">Có lỗi khi cập nhật site map</div>';
		}
		echo $result; die();
	}

	public function doAjaxAutoMark(){
		$objSeopage 				= new HT_Model_administrator_models_seopage();
		$result						= $objSeopage->autoMark(200);
		echo '<div class="auto_result">'.$result.'</div><div class="auto_result_text">Từ khóa đã được đánh dấu</div>';die();
	}

	public function doAjaxAutoLink(){
		$objSeopage 				= new HT_Model_administrator_models_seopage();
		$result						= $objSeopage->autoLinkContent(1000);
		echo '<div class="auto_result">'.$result.'</div><div class="auto_result_text">Từ khóa được khớp với bài viết gốc</div>';die();
	}

	public function autolinkAction(){
		$objSeopage 				= new HT_Model_administrator_models_seopage();
		$totalLinked				= $objSeopage->autoLinkContent(1000);
		$this->view->totalLinked 	= $totalLinked;
	}

	public function automarkAction(){
		$objSeopage 				= new HT_Model_administrator_models_seopage();
		$totalMark					= $objSeopage->autoMark(200);
		$this->view->totalMark 	= $totalMark;
	}

	public function sitemapAction(){
		$objUtil 					= new HT_Model_administrator_models_utility();
		$sitemapData 				= $this->buildXMLSitemap();
		$filePath					= ROOT_PATH.'/public/sitemap/sitemap.xml';
		$message					= $objUtil->overWriteFile($filePath,$sitemapData);
		$this->view->message 		= $message;
	}

	public function buildXMLSitemap(){
		$objSeogroup 	= new HT_Model_administrator_models_seogroup();
		$objSeopage 	= new HT_Model_administrator_models_seopage();
		$objSeo 		= new HT_Model_administrator_models_seo();
		$objNews 		= new HT_Model_administrator_models_news();
		$objConvert 	= new HT_Model_administrator_models_convert();
		$seoLink		= $objSeopage->getAllSeoPage();
		$data = '<?xml version="1.0" encoding="UTF-8"?>'."\r\n";
		$data .= '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">'."\r\n";

		$data .= '<url>'."\r\n";
		$data .= '<loc>http://wish.vn/mang-xa-hoi-tu-van-cham-soc-suc-khoe-wish.html</loc>'."\r\n";
		$data .= '<lastmod>'.date('Y-m-d').'</lastmod>'."\r\n";
		$data .= ' <changefreq>daily</changefreq>'."\r\n";
		$data .= '<priority>0.8</priority>'."\r\n";
		$data .= '</url>'."\r\n";

		if(is_array($seoLink) && sizeof($seoLink) >0){
			foreach((array)$seoLink as $seo){
				$data .= '<url>'."\r\n";
				$data .= '<loc>'.WEB_PATH.'/nen-doc/'.$objConvert->utf8_to_url($seo['tag_title']).'-'.$seo['seopage_id'].'.html</loc>'."\r\n";
				$data .= '<lastmod>'.date('Y-m-d').'</lastmod>'."\r\n";
				$data .= ' <changefreq>daily</changefreq>'."\r\n";
				$data .= '<priority>0.8</priority>'."\r\n";
				$data .= '</url>'."\r\n";
			}
		}

		
		$newsLink = $objNews->getNewsForSitemap();
		if(is_array($newsLink) && sizeof($newsLink) >0){
			foreach((array)$newsLink as $news){
				$data .= '<url>'."\r\n";
				$data .= '<loc>'.WEB_PATH.'/tin-tuc/chi-tiet/'.$news['newsId'].'/'.$objConvert->utf8_to_url($news['title']).'.html</loc>'."\r\n";
				$data .= '<lastmod>'.date('Y-m-d').'</lastmod>'."\r\n";
				$data .= ' <changefreq>daily</changefreq>'."\r\n";
				$data .= '<priority>0.8</priority>'."\r\n";
				$data .= '</url>'."\r\n";
			}
		}


		$seoLink = $objSeo->getAllSeoLink();
		if(is_array($seoLink) && sizeof($seoLink) >0){
			foreach((array)$seoLink as $seo){
				$data .= '<url>'."\r\n";
				$data .= '<loc>'.$seo['url'].'</loc>'."\r\n";
				$data .= '<lastmod>'.date('Y-m-d').'</lastmod>'."\r\n";
				$data .= ' <changefreq>daily</changefreq>'."\r\n";
				$data .= '<priority>0.8</priority>'."\r\n";
				$data .= '</url>'."\r\n";
			}
		}


		$groupLink = $objSeogroup->getTodaySeoGroup();
		if(is_array($groupLink) && sizeof($groupLink) >0){
			foreach((array)$groupLink as $group){
				$data .= '<url>'."\r\n";
				$data .= '<loc>'.WEB_PATH.'/chu-de-nen-doc/'.$objConvert->utf8_to_url($group['subject']).'-'.$group['group_id'].'.html</loc>'."\r\n";
				$data .= '<lastmod>'.date('Y-m-d').'</lastmod>'."\r\n";
				$data .= ' <changefreq>daily</changefreq>'."\r\n";
				$data .= '<priority>0.8</priority>'."\r\n";
				$data .= '</url>'."\r\n";
			}
		}


		$data .= '</urlset>'."\r\n";
		return $data;
	}

	public function newsAction(){
		$do = @$this->_request->getParam('do');
		$do = trim($do);
		if($do == 'list'){
			$this->getListNews();
		}else{
			$keyword 				= $this->_request->getParam('keyword');
			$this->view->keyword 	= $keyword;
			$this->view->inlineScript()->appendFile(WEB_PATH.'/application/modules/administrator/views/scripts/seopage/news.js');
		}

	}

	public function keywordAction(){
		$do = @$this->_request->getParam('do');
		$do = trim($do);
		if($do == 'delete'){
			$this->setKeywords(0);
		}elseif($do == 'recovery'){
			$this->setKeywords(1);
		}elseif($do == 'setPriority'){
			$this->setPriority(1);
		}elseif($do == 'removePriority'){
			$this->setPriority(5);
		}elseif($do == 'list'){
			$this->getListKeyword();
		}elseif($do == 'setData'){
			$this->setSeopageData();
		}else{
			$keyword 				= $this->_request->getParam('keyword');
			$this->view->keyword 	= $keyword;
			$this->view->inlineScript()->appendFile(WEB_PATH.'/application/modules/administrator/views/scripts/seopage/keyword.js');
		}

	}

	public function autoAction(){
		$this->view->inlineScript()->appendFile(WEB_PATH.'/application/modules/administrator/views/scripts/seopage/auto.js');
	}

	public function reportAction(){
		$do = @$this->_request->getParam('do');
		$do = trim($do);
		if($do == 'list'){
			$this->getReport();
		}else{
			$keyword 				= $this->_request->getParam('keyword');
			$this->view->keyword 	= $keyword;
			$this->view->inlineScript()->appendFile(WEB_PATH.'/application/modules/administrator/views/scripts/seopage/report.js');
		}
	}

	function setKeywords($isKeyword){
		$objSeopage = new HT_Model_administrator_models_seopage();
		$ids 		= $this->_request->getParam('ids');
		$idList		= array();
		foreach((array)$ids as $id){
			$idList[] = $id;
		}
		if(is_array($idList) && sizeof($idList) >0){
			$objSeopage->setKeywords($isKeyword,$idList);
		}
		echo 1;die();
	}

	function setPriority($priority){
		$objSeopage = new HT_Model_administrator_models_seopage();
		$ids 		= $this->_request->getParam('ids');
		$idList		= array();
		foreach((array)$ids as $id){
			$idList[] = $id;
		}
		if(is_array($idList) && sizeof($idList) >0){
			$objSeopage->setPriority($priority,$idList);
		}
		echo 1;die();
	}

	function setSeopageData(){
		$objSeopage 		= new HT_Model_administrator_models_seopage();
		$seopageIds 		= $this->_request->getParam('seopage_ids');
		$keywordList 		= $this->_request->getParam('secondary_keyword');
		$tagList 			= $this->_request->getParam('seo_tags');

		$seoDatas		= array();
		for($i=0;$i<sizeof($seopageIds);$i++){
			$seoDatas[] = array('seopage_id'=>$seopageIds[$i],'secondary_keyword'=>$keywordList[$i],'seo_tags'=>$tagList[$i]);
		}

		if(is_array($seoDatas) && sizeof($seoDatas) >0){
			$objSeopage->setSeoDatas($seoDatas);
		}
		echo 1;die();
	}


	public function importAction(){
		if(isset($_FILES['fileUpload'])){
			$objUtil 		= new HT_Model_administrator_models_utility();
			$path			= ROOT_PATH.'/public/uploads/keywords/';
			$csvPath		= ROOT_PATH.'/public/uploads/keywords/csv/';
			$maxFileSize 	= 5*1024*1024;
			$fileTypeAllow	= 'xlsx,zip';
			$fileName = $objUtil->importKeywords('fileUpload', $path, $maxFileSize, $fileTypeAllow);
			if($fileName == 'csv.zip'){
				$this->buildKeywordFile($path,$csvPath);
			}
			$this->_importKeywords();
			$this->_redirect(WEB_PATH.'/administrator/seopage/keyword');
		}
	}

	public function buildKeywordFile($path,$csvPath){
		header('Content-Type: text/html; charset=UTF-8');
		$objUtil 		= new HT_Model_administrator_models_utility();
		$files			= $objUtil->readFiles($csvPath);
		$csvContent		= null;
		foreach((array)$files as $file){
			chmod($file, 0777);
			$csvContent .= file_get_contents($file)."\r";
		}
		$csvContent = mb_convert_encoding($csvContent, 'UTF-8', 'UCS-2');
		$arrData = explode("\r", $csvContent);
		$keywords = array();
		foreach($arrData as $item){
			$item = trim($item);
			$item = str_replace('	', '__XXX__', $item);
			@list($keyword,$competition,$search) = @explode('__XXX__', $item);
			$keyword 		= trim($keyword);
			$competition 	= trim($competition);
			$search 		= trim($search);
			if(!$keyword || !$competition || !$search || $competition =='Competition'){
				// do nothing
			}else{
				$keywords[] 	= array($keyword,$competition,$search);
			}

		}
		$this->writeExcelFile($keywords,$path);
	}

	public function writeExcelFile($keywords,$path){
		//echo "<pre>";
		//print_r($keywords); die();
		include 'PHPExcel.php';
		// Create new PHPExcel object
		$objPHPExcel = new PHPExcel();
		// Set document properties
		$objPHPExcel->getProperties()->setCreator("Maarten Balliauw")
		->setLastModifiedBy("Maarten Balliauw")
		->setTitle("PHPExcel Test Document")
		->setSubject("PHPExcel Test Document")
		->setDescription("Test document for PHPExcel, generated using PHP classes.")
		->setKeywords("office PHPExcel php")
		->setCategory("Test result file");


		$sheet = $objPHPExcel->setActiveSheetIndex(0);
		for($i=0;$i<sizeof($keywords);$i++){
			$j = $i + 1;
			$sheet->setCellValue('A'.$j, $keywords[$i][0])->setCellValue('B'.$j, $keywords[$i][1])->setCellValue('C'.$j, $keywords[$i][2]);
		}
		$objPHPExcel->getActiveSheet()->setTitle('keywords');
		$objPHPExcel->setActiveSheetIndex(0);
		$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
		$objWriter->save($path.'keywords.xlsx');
	}



	private function _importKeywords(){
		include 'PHPExcel.php';
		$objSeopage 	= new HT_Model_administrator_models_seopage();
		$excelFile	 	= ROOT_PATH.'/public/uploads/keywords/keywords.xlsx';
		chmod($excelFile, 0777);
		$objPHPExcel 	= PHPExcel_IOFactory::load($excelFile);
		$sheetData 	 	= $objPHPExcel->getActiveSheet()->toArray(null,true,true,true);
		$keywords		= array();
		for($i=1;$i<=sizeof($sheetData);$i++){
			$keywords[] = array(strtolower(trim($sheetData[$i]['A'])),$sheetData[$i]['B']*100,$sheetData[$i]['C']);
		}
		if(is_array($keywords) && sizeof($keywords) >0){
			$objSeopage->updateKeywords($keywords);
		}
	}

	public function updateAction(){
		$objSeopage 	= new HT_Model_administrator_models_seopage();
		$objUtil 		= new HT_Model_administrator_models_utility();
		$do 		 	= @$this->_request->getParam('do');
		$id 			= (int)$this->_request->getParam('id');
		$status 		= (int)$this->_request->getParam('status');
		@$auth 			= Zend_Auth::getInstance();
		$user 			= @$auth->getStorage()->read();
		$wishid			= $user->wishid;


		$show_id 			= 2;
		$reference_news_id 	= null;
		$pageUrl			= null;
		if($do == 'submit'){
			$data = array();
			$data['show_id'] 				= $this->_request->getParam('show_id');
			$data['priority'] 				= (int)$this->_request->getParam('priority');
			$data['tag_title'] 				= $this->_request->getParam('tag_title');
			$data['seo_tags'] 				= $this->_request->getParam('seo_tags');
			$data['tag_description'] 		= $this->_request->getParam('tag_description');
			$data['title'] 					= $this->_request->getParam('title');
			$data['content'] 				= $this->_request->getParam('content');
			$data['reference_news_id'] 		= $this->_request->getParam('reference_news_id');
			$data['link_type_id'] 	   		= 1;
			if($id >0){
				$data['date_updated'] 			= date('Y-m-d H:i:s');
				$data['admin_update_id'] 		= $wishid;
				$return = $objSeopage->updateData($data,$id);
			}else{
				$data['date_created'] 			= date('Y-m-d H:i:s');
				$data['date_updated'] 			= date('Y-m-d H:i:s');
				$data['admin_create_id'] 		= $wishid;
				$return = $objSeopage->addData($data);
			}

			if($return > 0){
				$this->_redirect(WEB_PATH.'/administrator/seopage/update?status=1&id='.$return);
			}else{
				$this->_redirect(WEB_PATH."/administrator/seopage/update?status=$return&id=$id");
			}

		}elseif($id >0){
			$objConvert				= new HT_Model_administrator_models_convert();
			$seopage 				= $objSeopage->getSeopage($id);
			$seopage_id				= (int)$seopage['seopage_id'];
			//$show_id				= (int)$seopage['show_id'];
			$show_id				= 2;
			$tag_title				= $seopage['tag_title'];
			$reference_news_id		= (int)$seopage['reference_news_id'];

			$pageUrl				= WEB_PATH.'/nen-doc/'.$objConvert->utf8_to_url($tag_title).'-'.$seopage_id.'.html';

			$this->view->seopage	= $seopage;
			$this->view->pageUrl	= $pageUrl;
		}

		$position 				= $objUtil->GetCombobox('show_id','show_id','show_name','seo_show',array('isBlankVal'=>'Vui lòng chọn vị trí hiển thị','defaultValue'=>$show_id));
		$news 					= $objUtil->GetCombobox('reference_news_id','id_news','title_vn','news',array('isBlankVal'=>'Vui lòng chọn tin lấy nội dung của tin được SEO - Hệ thống sẽ gắn từ khóa hiện tại vào tin này','defaultValue'=>$reference_news_id,'orderBy'=>'title_vn'));

		$this->view->id 		= $id;
		$this->view->status 	= $status;
		$this->view->position 	= $position;
		$this->view->news 		= $news;
		$this->view->inlineScript()->appendFile(WEB_PATH.'/application/modules/administrator/views/scripts/seopage/update.js');
	}

	function deleteSeopage($id){
		$objSeopage = new HT_Model_administrator_models_seopage();
		echo $objSeopage->delete("seopage_id=".(int)$id);die();
	}

	private function _getListNews_Filter(){
		$keyword 		= trim($this->_request->getParam('keyword'));
		$searchFor 		= $this->_request->getParam('search_for');

		$filter = array('denied_ids'=>$this->deniedIds);
		if($keyword) $filter['keyword'] = $keyword;
		if(in_array($searchFor,array('not_connected','connected','has_keys','no_keys'))) $filter['search_for'] = $searchFor;

		return $filter;
	}

	function getListNews(){
		$objUtil 		= new HT_Model_administrator_models_utility();
		$objConvert		= new HT_Model_administrator_models_convert();
		$objSeopage 	= new HT_Model_administrator_models_seopage();
		$page 			= (int)$this->_request->getParam('page');

		$size 			= PAGING_SIZE;
		if (!is_numeric($page) || $page <= 0) {
			$page = 1;
		}
		$start = $page * $size - $size;

		$filter = $this->_getListNews_Filter();


		$totalRecord = $objSeopage->getListNews_nb($filter);
		$listNews = $objSeopage->getListNews($start,$size,$filter);
		$paging = trim($objUtil->paging($page, $size, $totalRecord));

		$ajaxData = null;
		if($paging){
			$ajaxData .= '<div class="paging_box">';
			$ajaxData .= $paging;
			$ajaxData .= '<div class="cb"></div></div>';
		}

		$ajaxData .= '<div class="ub_button_list2 fr">';
		//$ajaxData .= '<div id="setRss"  class="ub_button1 fl">';
		//$ajaxData .= 'Cập nhật RSS';
		//$ajaxData .= '</div>';
		$ajaxData .= '<div id="setNewsKeywords"  class="ub_button1 fl">';
		$ajaxData .= 'Cập nhật từ khóa';
		$ajaxData .= '</div>';
		$ajaxData .= '<div class="cb"></div></div><div class="cb"></div><br>';

		$ajaxData .= '<table cellspacing="0" class="tablesorter tablesorterBorder">';
		$ajaxData .= '<thead>';
		$ajaxData .= '<tr>';
		$ajaxData .= '<th width="15">STT</th>';
		//$ajaxData .= '<th width="30">RSS</th>';
		$ajaxData .= '<th width="400">Tiêu đề tiếng việt</th>';
		$ajaxData .= '<th width="500">Danh sách từ khóa cho SEO - Cách nhau bởi dấu ","</th>';
		$ajaxData .= '<th style="white-space: nowrap;padding-right: 5px;" align="center">Điều khiển</th>';
		$ajaxData .= '</tr>';
		$ajaxData .= '</thead>';

		$i=0;
		foreach($listNews as $news){
			$url = WEB_PATH."/tin-tuc/chi-tiet/".$news['newsId']."/".$objConvert->utf8_to_url($news['newsTitle']).".html";
			$i++;
			$trClass = null;
			if($i%2 == 1) $trClass = ' class="altrow"';
			$ajaxData .= '<tr id="'.$news['newsId'].'" '.$trClass.'>';
			$ajaxData .= '<input type="hidden" name="ids[]" value="'.$news['newsId'].'" />';
			$ajaxData .= '<td align="center">'.$i.'</td>';
			//$rssChecked = null;
			//if($news['rss']) $rssChecked = 'checked="checked"';
			//$ajaxData .= '<td><input type="checkbox" name="rss[]" '.$rssChecked.'></td>';
			$ajaxData .= '<td><a href="'.$url.'" target="_blank">'.$news['newsTitle'].'</a></td>';
			$ajaxData .= '<td><input id="seo_keywords'.$i.'" style = "width:500px; border:solid 1px #AAAAAA;" type="text" name="seo_keywords[]" value="'.$news['seo_keywords'].'" /></td>';
			$ajaxData .= '<td style="white-space: nowrap" align="center">';
			$ajaxData .= '<a target="_blank" href="'.WEB_PATH.'/administrator/news/edit/id/'.$news['newsId'].'">Cập nhật</a>';
			$ajaxData .= '</td>';
			$ajaxData .= '</tr>';
		}
		$ajaxData .= '</tbody>';
		$ajaxData .= '</table>';
		$ajaxData .= '</div>';
		if($paging){
			$ajaxData .= '<div class="paging_box">';
			$ajaxData .= $paging;
			$ajaxData .= '<div class="cb"></div></div>';
		}

		$searchResult = "Có <b>".number_format($totalRecord, 0, '.', ',')."</b> Kết quả phù hợp với dữ liệu tìm kiếm";
		echo $ajaxData.':::'.$searchResult; die();
	}

	function exportNewsKeywords(){
		$objSeopage 	= new HT_Model_administrator_models_seopage();

		$filter = $this->_getListNews_Filter();
		$listNews = $objSeopage->getListNews(0,999999999,$filter);

		$ajaxData = '<div class="keyword_box">';
		$ajaxData .= '<textarea>';
		$arrKeys = array();
		foreach((array)$listNews as $news){
			$keywords = strtolower(trim($news['seo_keywords']));
			$arr = explode(',', $keywords);
			foreach ((array)$arr as $key){
				$key 	= trim($key);
				if($key && !in_array($key,$arrKeys)){
					$arrKeys[] = $key;
					$ajaxData .= $key."\r\n";
				}
			}
		}
		$ajaxData .= '</textarea>';
		$ajaxData .= '<div class="cb"></div>';
		$ajaxData .= '</div>';
		$ajaxData .= '<div class="cb"></div>';
			
		echo $ajaxData; die();
	}

	function getReport(){
		$objUtil 		= new HT_Model_administrator_models_utility();
		$objConvert		= new HT_Model_administrator_models_convert();
		$objSeopage 	= new HT_Model_administrator_models_seopage();
		$keyword 		= trim($this->_request->getParam('keyword'));
		$orderBy 		= $this->_request->getParam('orderBy');
		$direction		= $this->_request->getParam('direction');
		$page 			= (int)$this->_request->getParam('page');
		$searchFrom 	= $this->_request->getParam('monthly_search_from');
		$searchTo 		= $this->_request->getParam('monthly_search_to');

		$size 			= PAGING_SIZE;
		if (!is_numeric($page) || $page <= 0) {
			$page = 1;
		}
		$start = $page * $size - $size;

		$filter = array('orderBy'=>$orderBy,'direction'=>$direction,'is_keyword'=>1);
		if($keyword) $filter['keyword'] = $keyword;
		if($searchFrom) $filter['monthly_search_from'] = $searchFrom;
		if($searchTo) $filter['monthly_search_to'] = $searchTo;

		$totalRecord = $objSeopage->getListSeopage_nb($filter);
		$listSeopage = $objSeopage->getListSeopage($start,$size,$filter);
		$paging = trim($objUtil->paging($page, $size, $totalRecord));

		$ajaxData = null;
		if($paging){
			$ajaxData .= '<div class="paging_box">';
			$ajaxData .= $paging;
			$ajaxData .= '<div class="cb"></div></div>';
		}

		$ajaxData .= '<table cellspacing="0" class="tablesorter tablesorterBorder">';
		$ajaxData .= '<thead>';
		$ajaxData .= '<tr>';
		$ajaxData .= '<th width="15">STT</th>';
		$ajaxData .= '<th width="300">Từ khóa</th>';
		$ajaxData .= '<th width="150">Tìm kiếm (Tháng)</th>';
		$ajaxData .= '<th width="100">Cạnh tranh</th>';
		$ajaxData .= '<th width="60">Ưu tiên</th>';
		$ajaxData .= '<th width="400">Đã gắn với tin</th>';
		$ajaxData .= '</tr>';
		$ajaxData .= '</thead>';

		$i=0;
		foreach($listSeopage as $seopage){
			$tagTitle 				= $seopage['tag_title'];
			$url					= WEB_PATH.'/nen-doc/'.$objConvert->utf8_to_url($tagTitle).'-'.$seopage['seopage_id'].'.html';
			$lengthTitle 			= strlen($tagTitle);
			$tagDescription			= $seopage['tag_description'];
			$lengthDescription 		= strlen($tagDescription);

			$i++;
			$trClass = null;
			if($i%2 == 1) $trClass = ' class="altrow"';
			$ajaxData .= '<tr id="'.$seopage['seopage_id'].'" '.$trClass.'>';
			$ajaxData .= '<td align="center">'.$i.'</td>';
			$ajaxData .= '<td><a href="'.$url.'" target="_blank">'.$tagTitle.'</a></td>';
			$ajaxData .= '<td align="right">'.number_format($seopage['monthly_search'], 0, '.', ',').'</td>';
			$ajaxData .= '<td align="center">'.$seopage['competition'].'</td>';
			$ajaxData .= '<td align="center">'.$seopage['priority'].'</td>';
			$ajaxData .= '<td align="left">'.$seopage['news_title'].'</td>';
			$ajaxData .= '</tr>';
		}
		$ajaxData .= '</tbody>';
		$ajaxData .= '</table>';
		$ajaxData .= '</div>';
		if($paging){
			$ajaxData .= '<div class="paging_box">';
			$ajaxData .= $paging;
			$ajaxData .= '<div class="cb"></div></div>';
		}
		$searchResult = "Có <b>".number_format($totalRecord, 0, '.', ',')."</b> kết quả phù hợp với điều kiện tìm kiếm";
		echo $ajaxData.':::'.$searchResult; die();
	}

	private function _getButtonList($searchFor,$position=null){
		$buttonList = '<div class="ub_button_list1">';
			
		switch($searchFor){
			case 1: // Từ khóa có bài viết
			case 2: // Từ khóa ưu tiên
			case 3: // Từ khóa bình thườngt
			case 9: // Google đã index nhưng bị sai
				$buttonList .= '<div id="setPriorityBtn'.$position.'"  class="ub_button fl">';
				$buttonList .= 'Set ưu tiên';
				$buttonList .= '</div>';
				$buttonList .= '<div id="removePriorityBtn'.$position.'"  class="ub_button fl">';
				$buttonList .= 'Bỏ ưu tiên';
				$buttonList .= '</div>';
				$buttonList .= '<div id="deleteBtn'.$position.'" class="ub_button fl">';
				$buttonList .= 'Xóa bỏ';
				$buttonList .= '</div>';
				$buttonList .= '<div id="updateBtn'.$position.'"  class="ub_button fl">';
				$buttonList .= 'Cập nhật';
				$buttonList .= '</div>';
				$buttonList .= '<div id="duplicateBtn'.$position.'" class="ub_button fl">';
				$buttonList .= 'Nhân bản';
				$buttonList .= '</div>';
				break;
			case 4:// Không phải từ khóa
				$buttonList .= '<div id="recoveryBtn'.$position.'"  class="ub_button fl">';
				$buttonList .= 'Khôi phục';
				$buttonList .= '</div>';
				break;
			case 5:// Không áp dụng bộ lọc
			case 6: // Google đã index
				break;
			case 7: // Google chưa index
				$buttonList .= '<div id="deleteBtn'.$position.'" class="ub_button fl">';
				$buttonList .= 'Xóa bỏ';
				$buttonList .= '</div>';
				$buttonList .= '<div id="removePriorityBtn'.$position.'"  class="ub_button fl">';
				$buttonList .= 'Bỏ ưu tiên';
				$buttonList .= '</div>';
				$buttonList .= '<div id="resendBtn'.$position.'" class="ub_button fl">';
				$buttonList .= 'Gửi lại google';
				$buttonList .= '</div>';
				break;
		}
			
		$buttonList .= '<div class="cb"></div>';
		$buttonList .= '</div>';
		$buttonList .= '<div class="cb"></div><br>';

		return $buttonList;
	}

	private function _getFilters($searchFor){
		$objSeopage 		= new HT_Model_administrator_models_seopage();
		$keyword 			= trim($this->_request->getParam('keyword'));
		$is_keyword 		= (int)$this->_request->getParam('is_keyword');
		$searchFrom 		= $this->_request->getParam('monthly_search_from');
		$searchTo 			= $this->_request->getParam('monthly_search_to');
		$charFrom 			= $this->_request->getParam('char_from');
		$charTo 			= $this->_request->getParam('char_to');
		$competitionFrom 	= $this->_request->getParam('competition_from');
		$competitionTo 		= $this->_request->getParam('competition_to');
		$sameFrom 			= $this->_request->getParam('same_from');
		$sameTo 			= $this->_request->getParam('same_to');
		$visitedFrom 			= $this->_request->getParam('visited_from');
		$visitedTo 			= $this->_request->getParam('visited_to');
		$orderBy 		= $this->_request->getParam('orderBy');
		$direction		= $this->_request->getParam('direction');

		$filter = array();
		if($orderBy != 'auto'){
			$filter['orderBy'] 			= $orderBy;
			$filter['direction'] 		= $direction;
		}
		if($keyword) $filter['keyword'] = $keyword;
		
		if($searchFrom) $filter['monthly_search_from'] 	= $searchFrom;
		if($searchTo) $filter['monthly_search_to'] 		= $searchTo;
		if($charFrom) $filter['char_from'] 	= $charFrom;
		if($charTo) $filter['char_to'] 		= $charTo;
		if($competitionFrom) $filter['competition_from'] 	= $competitionFrom;
		if($competitionTo) $filter['competition_to'] 		= $competitionTo;
		if($sameFrom) $filter['same_from'] 					= $sameFrom;
		if($sameTo) $filter['same_to'] 						= $sameTo;
		if($visitedFrom) $filter['visited_from'] 			= $visitedFrom;
		if($visitedTo) $filter['visited_to'] 				= $visitedTo;

		switch($searchFor){
			case 1: // Từ khóa có bài viết
				$filter['reference_news_id'] 	= 0;
				$filter['is_keyword'] 	= 1;
				$filter['is_mark'] 		= 1;
				$filter['has_mark'] 	= 1;
				$filter['no_priority'] 	= 1;
				break;
			case 2: // Từ khóa ưu tiên
				$filter['reference_news_id'] 	= 0;
				$filter['is_keyword'] 			= 1;
				$filter['priority'] 			= 1;
				break;
			case 3: // Từ khóa bình thường
				$filter['reference_news_id'] 	= 0;
				$filter['is_keyword'] 	= 1;
				$filter['no_priority'] 	= 1;
				break;
			case 4: // Không phải từ khóa
				$filter['reference_news_id'] 	= 0;
				$filter['is_keyword'] 	= 0;
				break;
			case 6: // Google đã index
				$filter['indexed'] 	= 1;
				break;
			case 7: // Google chưa index
				$filter['not_index'] 	= 1;
				$filter['time_ago'] 	= 1;
				break;
			case 8: //Bài gửi hôm nay
				$filter['has_news'] 			= 1;
				$filter['is_keyword'] 			= 1;
				$filter['priority'] 			= 1;
				$filter['date_updated'] 		= date('Y-m-d');
				break;
			case 9: //Google đã index nhưng bị error 404
				$filter['reference_news_id'] 	= 0; // Không có tin nào được gắn
				$filter['is_google_index'] 		= 1; // Nhưng đã báo là good index rồi.
				$filter['time_ago'] 			= 1; // Ngay cap nhat truoc hom nay
				break;
		}
		return $filter;
	}
	
	public function exportKeywords(){
		$objSeopage 	= new HT_Model_administrator_models_seopage();
		$searchFor 		= $this->_request->getParam('search_for');
		$filter 		= $this->_getFilters($searchFor);
		$listSeopage 	= $objSeopage->getListSeopage(0,999999999,$filter);
			
		$ajaxData = '<div class="keyword_box">';
		$ajaxData .= '<textarea>';
		foreach((array)$listSeopage as $seopage){
			$keyword = trim(strtolower($seopage['tag_title']));
			if($keyword) $ajaxData .= $keyword."\r\n";
		}
		$ajaxData .= '</textarea>';
		$ajaxData .= '<div class="cb"></div>';
		$ajaxData .= '</div>';
		$ajaxData .= '<div class="cb"></div>';
			
		echo $ajaxData; die();
			
	}

	function getListKeyword(){
		$objUtil 		= new HT_Model_administrator_models_utility();
		$objConvert		= new HT_Model_administrator_models_convert();
		$objSeopage 	= new HT_Model_administrator_models_seopage();
		$searchFor 		= $this->_request->getParam('search_for');
		$updateSame		= $this->_request->getParam('update_same_key');
		$page 			= (int)$this->_request->getParam('page');
		$size 			= PAGING_SIZE;
		if (!is_numeric($page) || $page <= 0) {
			$page = 1;
		}
		$start = $page * $size - $size;

		$filter = $this->_getFilters($searchFor);
		
		if($updateSame == 'on'){
			$objSeopage->updateSameInfo($searchFor);
		}

		$totalRecord = $objSeopage->getListSeopage_nb($filter);
		$listSeopage = $objSeopage->getListSeopage($start,$size,$filter);
		$paging = trim($objUtil->paging($page, $size, $totalRecord));

		$ajaxData = null;
		if($paging){
			$ajaxData .= '<div class="paging_box">';
			$ajaxData .= $paging;
			$ajaxData .= '<div class="cb"></div></div>';
		}

		$ajaxData .= $this->_getButtonList($searchFor);

		$ajaxData .= '<table cellspacing="0" class="tablesorter tablesorterBorder">';
		$ajaxData .= '<thead>';
		$ajaxData .= '<tr>';
		$ajaxData .= '<th width="5">STT</th>';
		$ajaxData .= '<th width="5"><input type="checkbox" id="chkCheckall" class="checkall" /></th>';
		$ajaxData .= '<th width="200">Từ khóa chính</th>';
		if($searchFor == 7){
			$ajaxData .= '<th width="700">Gắn với bài viết</th>';
		}else{
			$ajaxData .= '<th width="200">Từ khóa phụ</th>';
			$ajaxData .= '<th width="40">Mark</th>';
			$ajaxData .= '<th width="40">Same</th>';
			$ajaxData .= '<th width="40">Visits</th>';
			$ajaxData .= '<th width="200">Từ khóa liên quan</th>';
		}
		$ajaxData .= '<th width="100">Tìm kiếm</th>';
		$ajaxData .= '<th width="120">Cạnh tranh</th>';
		$ajaxData .= '<th style="white-space: nowrap;padding-right: 5px;" align="center">Điều khiển</th>';
		$ajaxData .= '</tr>';
		$ajaxData .= '</thead>';

		$i=0;
		foreach($listSeopage as $seopage){
			$tagTitle 				= $seopage['tag_title'];
			$url					= WEB_PATH.'/nen-doc/'.$objConvert->utf8_to_url($tagTitle).'-'.$seopage['seopage_id'].'.html';
			$newsUrl				= WEB_PATH.'/tin-tuc/chi-tiet/'.$seopage['reference_news_id'].'/'.$objConvert->utf8_to_url($seopage['news_title']).'.html';
			$lengthTitle 			= strlen($tagTitle);
			$tagDescription			= $seopage['tag_description'];
			$lengthDescription 		= strlen($tagDescription);

			$i++;
			$trClass = null;
			if($i%2 == 1) $trClass = ' class="altrow"';
			$ajaxData .= '<tr id="'.$seopage['seopage_id'].'" '.$trClass.'>';
			$ajaxData .= '<input type="hidden" name="seopage_ids[]" value="'.$seopage['seopage_id'].'" />';
			$ajaxData .= '<td align="center">'.$i.'</td>';
			$ajaxData .= '<td align="center"><input type="checkbox" name="ids[]" value="'.$seopage['seopage_id'].'" /></td>';
			$ajaxData .= '<td><a href="'.$url.'" target="_blank">'.$tagTitle.'</a></td>';
			if($searchFor == 7){
				// Google chưa index
				$ajaxData .= '<td><a href="'.$newsUrl.'" target="_blank">'.$seopage['news_title'].'</a></td>';
			}else{
				$ajaxData .= '<td><input id="secondary_keyword'.$i.'" class="secondary_keyword" style = "width:150px; border:solid 1px #AAAAAA;" type="text" name="secondary_keyword[]" value="'.$seopage['secondary_keyword'].'" /></td>';
				$ajaxData .= '<td align="center"><span style="font-weight:bold;color:#FF0000">'.$seopage['total_mark'].'</span></td>';
				$ajaxData .= '<td align="center"><span style="font-weight:bold;color:#FF0000">'.$seopage['total_same_key'].'</span></td>';
				$ajaxData .= '<td align="center"><span style="font-weight:bold;color:#FF0000">'.$seopage['visited'].'</span></td>';
				$ajaxData .= '<td><input id="seo_tags'.$i.'" class="seo_tags" style = "width:200px; border:solid 1px #AAAAAA;" type="text" name="seo_tags[]" value="'.$seopage['seo_tags'].'" /></td>';
			}

			$ajaxData .= '<td align="right">'.number_format($seopage['monthly_search'], 0, '.', ',').'</td>';
			$ajaxData .= '<td align="center">'.$seopage['competition'].'</td>';
			$ajaxData .= '<td style="white-space: nowrap" align="center">';
			$ajaxData .= '<a href="'.WEB_PATH.'/administrator/seopage/update/?id='.$seopage['seopage_id'].'">Gắn tin</a>';
			$ajaxData .= '</td>';
			$ajaxData .= '</tr>';
		}
		$ajaxData .= '</tbody>';
		$ajaxData .= '</table>';
		$ajaxData .= '</div>';
		if($paging){
			$ajaxData .= '<div class="paging_box">';
			$ajaxData .= $paging;
			$ajaxData .= '<div class="cb"></div></div>';
		}

		$ajaxData .= '<div class="cb"></div>';
		$ajaxData .= $this->_getButtonList($searchFor,1);

		$searchResult = "Có <b>".number_format($totalRecord, 0, '.', ',')."</b> kết quả phù hợp với điều kiện tìm kiếm";
		echo $ajaxData.':::'.$searchResult; die();
	}

	function getListSeopage(){
		$objUtil 		= new HT_Model_administrator_models_utility();
		$objConvert		= new HT_Model_administrator_models_convert();
		$objSeopage 	= new HT_Model_administrator_models_seopage();
		$keyword 		= trim($this->_request->getParam('keyword'));
		$is_keyword 	= (int)$this->_request->getParam('is_keyword');
		$searchFrom 	= $this->_request->getParam('monthly_search_from');
		$searchTo 		= $this->_request->getParam('monthly_search_to');

		$orderBy 		= $this->_request->getParam('orderBy');
		$direction		= $this->_request->getParam('direction');
		$page 			= (int)$this->_request->getParam('page');
		$size 			= PAGING_SIZE;
		if (!is_numeric($page) || $page <= 0) {
			$page = 1;
		}
		$start = $page * $size - $size;

		$filter = array('orderBy'=>$orderBy,'direction'=>$direction,'is_keyword'=>1,'news_linked'=>true);
		if($keyword) $filter['keyword'] = $keyword;
		if($searchFrom) $filter['monthly_search_from'] = $searchFrom;
		if($searchTo) $filter['monthly_search_to'] = $searchTo;

		$totalRecord = $objSeopage->getListSeopage_nb($filter);
		$listSeopage = $objSeopage->getListSeopage($start,$size,$filter);
		$paging = trim($objUtil->paging($page, $size, $totalRecord));

		$ajaxData = null;
		if($paging){
			$ajaxData .= '<div class="paging_box">';
			$ajaxData .= $paging;
			$ajaxData .= '<div class="cb"></div></div>';
		}
		$ajaxData .= '<table cellspacing="0" class="tablesorter tablesorterBorder">';
		$ajaxData .= '<thead>';
		$ajaxData .= '<tr>';
		$ajaxData .= '<th width="15">STT</th>';
		$ajaxData .= '<th width="200">Tag title</th>';
		$ajaxData .= '<th width="300">Tag description</th>';
		$ajaxData .= '<th width="200">Title sau khi ghép</th>';
		$ajaxData .= '<th width="100">Search</th>';
		$ajaxData .= '<th style="white-space: nowrap;padding-right: 5px;" align="center">Điều khiển</th>';
		$ajaxData .= '</tr>';
		$ajaxData .= '</thead>';

		$i=0;
		foreach($listSeopage as $seopage){
			$tagTitle 				= $seopage['tag_title'];
			$url					= WEB_PATH.'/nen-doc/'.$objConvert->utf8_to_url($tagTitle).'-'.$seopage['seopage_id'].'.html';
			$lengthTitle 			= strlen($tagTitle);
			$tagDescription			= $seopage['tag_description'];
			$lengthDescription 		= strlen($tagDescription);

			$i++;
			$trClass = null;
			if($i%2 == 1) $trClass = ' class="altrow"';
			$ajaxData .= '<tr id="'.$seopage['seopage_id'].'" '.$trClass.'>';
			$ajaxData .= '<td align="center">'.$i.'</td>';
			$ajaxData .= '<td><a href="'.$url.'" target="_blank">'.$tagTitle.'</a></td>';
			$ajaxData .= '<td>'.$tagDescription.'</td>';
			$ajaxData .= '<td>'.$seopage['news_title'].'. '.$seopage['title'].'</td>';
			$ajaxData .= '<td>'.number_format($seopage['monthly_search'], 0, '.', ',').'</td>';
			$ajaxData .= '<td style="white-space: nowrap" align="center">';
			$ajaxData .= '<a href="#" onclick="deleteSeopage('.$seopage['seopage_id'].')">Xóa</a> | <a href="'.WEB_PATH.'/administrator/seopage/update/?id='.$seopage['seopage_id'].'">Sửa</a>';
			$ajaxData .= '</td>';
			$ajaxData .= '</tr>';
		}
		$ajaxData .= '</tbody>';
		$ajaxData .= '</table>';
		$ajaxData .= '</div>';
		if($paging){
			$ajaxData .= '<div class="paging_box">';
			$ajaxData .= $paging;
			$ajaxData .= '<div class="cb"></div></div>';
		}

		$searchResult = "Có <b>".number_format($totalRecord, 0, '.', ',')."</b> kết quả phù hợp với điều kiện tìm kiếm";
		echo $ajaxData.':::'.$searchResult; die();
	}

	function exportKeyword(){
		$filePath 		= ROOT_PATH.'/public/seo/keywords.txt';
		$objUtil 		= new HT_Model_administrator_models_utility();
		$objConvert		= new HT_Model_administrator_models_convert();
		$objSeopage 	= new HT_Model_administrator_models_seopage();
		$keyword 		= trim($this->_request->getParam('keyword'));
		$is_keyword 	= (int)$this->_request->getParam('is_keyword');
		$searchFrom 	= $this->_request->getParam('monthly_search_from');
		$searchTo 		= $this->_request->getParam('monthly_search_to');

		$orderBy 		= $this->_request->getParam('orderBy');
		$direction		= $this->_request->getParam('direction');

		$start 			= 0;
		$size			= 99999999;

		$filter = array('orderBy'=>$orderBy,'direction'=>$direction,'is_keyword'=>1,'news_linked'=>true);
		if($keyword) $filter['keyword'] = $keyword;
		if($searchFrom) $filter['monthly_search_from'] = $searchFrom;
		if($searchTo) $filter['monthly_search_to'] = $searchTo;

		$totalRecord = $objSeopage->getListSeopage_nb($filter);
		$listSeopage = $objSeopage->getListSeopage($start,$size,$filter);
		$keywordList = null;
		foreach((array)$listSeopage as $sp){
			$keywordList .= trim($sp['tag_title'])."\r\n";
		}
		$objUtil->overWriteFile($filePath,$keywordList);
		echo $totalRecord; die();
	}
}
